<?php

use console\db\Migration;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Console;

/**
 * 初始化类型数据
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m200110_001121_d_staff extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%staff}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        if (!$this->isExistsTable($this->tableName)) {
            return false;
        }
        $this->compact = true;
        $data = $this->getData('staff.php');
        $count = count($data);
        Console::startProgress($i = 0, $count);
        /* @var $security \common\base\Security */
        $security = Yii::$app->security;
        foreach ($data as $item) {
            list($realname, $mobile, $companyId) = $item;
            $uniMobile = $security->generatePrivateKey($mobile);
            $staff = (new Query())->from($this->tableName)->andWhere(['mobile' => $uniMobile])->one();
            if ($staff) {
                $this->update($this->tableName, [
                    'realname' => $realname,
                    'mobile' => $uniMobile,
                    'mobile_hash' => $security->encryptMaster($mobile),
                    'company_id' => intval($companyId),
                ], [
                    'id' => $staff['id']
                ]);
                if ($staff['user_id']) {
                    $this->update('{{%user}}', [
                        'company_id' => intval($companyId),
                    ], [
                        'id' => $staff['user_id']
                    ]);
                }
            } else {
                $this->insert($this->tableName, [
                    'realname' => $realname,
                    'mobile' => $uniMobile,
                    'mobile_hash' => $security->encryptMaster($mobile),
                    'company_id' => intval($companyId),
                    'status' => 0,
                    'created_at' => time(),
                    'updated_at' => time(),
                ]);
            }
            $i++;
            Console::updateProgress($i, $count);
        }
        Console::endProgress("update done." . PHP_EOL);
    }

}
